package com.example.springboot.security;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.example.springboot.mybatis.mapper.base.TbUserMapper;
import com.example.springboot.mybatis.mapper.myextend.PermissionDao;
import com.example.springboot.pojo.base.TbPermission;
import com.example.springboot.pojo.base.TbUser;
import com.example.springboot.pojo.base.TbUserExample;
import com.example.springboot.pojo.base.TbUserExample.Criteria;
import com.example.springboot.pojo.myextend.TbUserChild;

/**
 * Created by yangyibo on 17/2/7.
 */
@Service
public class UrlUserService implements UserDetailsService {
	private static final String salt = "mysalt";

	@Autowired
	private TbUserMapper userMapper;
	@Autowired
	private PermissionDao permissionMapper;

	@Override
	public TbUserChild loadUserByUsername(String userName) {
		TbUserExample userExample = new TbUserExample();
		Criteria criteria = userExample.createCriteria();
		criteria.andUsernameEqualTo(userName);

		List<TbUser> userList = userMapper.selectByExample(userExample);
		if (userList.size() != 0) {
			TbUser user = userList.get(0);

			TbUserChild userChild = new TbUserChild();

			try {
				BeanUtils.copyProperties(userChild, user);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}

			List<TbPermission> permissions = permissionMapper.getByUserId(user.getId());
			List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
			for (TbPermission permission : permissions) {
				if (permission != null && permission.getName() != null) {
					GrantedAuthority grantedAuthority = new UrlGrantedAuthority(permission.getUrl(),
							permission.getMethod());
					grantedAuthorities.add(grantedAuthority);
				}
			}
			userChild.setGrantedAuthorities(grantedAuthorities);

			return userChild;
		} else {

			throw new UsernameNotFoundException("admin: " + userName + " do not exist!");
		}
	}
}